package com.cch.cooperation.common.web.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import org.apache.catalina.connector.ClientAbortException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.net.URLEncoder;

public class ResponseUtil {

    public static void resultJson(HttpServletResponse response, Object data) throws IOException {
        String json = JSON.toJSONString(data);
        if (StrUtil.isNotEmpty(response.getContentType())) {
            response.setContentType(response.getContentType().replace("text/html", "application/json"));
        } else {
            response.setContentType("application/json;charset=utf-8");
        }
        try (Writer writer = response.getWriter()) {
            writer.write(json);
            writer.flush();
        }
    }

    public static void download(HttpServletRequest request, HttpServletResponse response, String filename, long size, InputStream inputStream) throws IOException {
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Connection", "keep-alive");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "utf-8"));
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
        // 计算断点加载位置
        long start = 0;
        long end = size - 1;
        String rangeStr = request.getHeader("Range");
        if (!StrUtil.isEmpty(rangeStr)) {
            String[] args = rangeStr.replace("bytes=", "").split("-");
            if (args.length > 1) {
                end = Long.parseLong(args[1]);
            }
            response.setHeader("Content-Range", "bytes " + args[0] + "-" + end + "/" + size);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            start = Long.parseLong(args[0]);
        }
        response.setHeader("Content-Length", String.valueOf(end - start + 1));
        try {
            inputStream.skip(start);
            try (OutputStream outputStream = response.getOutputStream()) {
                int len;
                byte[] buff = new byte[1024 * 128];
                while ((len = inputStream.read(buff)) != -1) {
                    outputStream.write(buff, 0, len);
                }
            }
        } catch (ClientAbortException e) {  // 客户端中断链接，不记录
            return;
        }
    }
}
